﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Agnes.Libaray;
using Agnes.Core;
using Caliburn.Micro;

namespace Agnes.MyDocsLib
{
    /// <summary>
    /// 新建文章命令
    /// </summary>
    class NewArticleCmd
    {
        private static NewArticleCmd _instance;

        /// <summary>
        /// 返回唯一实例
        /// </summary>
        public static NewArticleCmd Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new NewArticleCmd();
                }
                return _instance;
            }
        }

        private RoutedCommand _requery;

        /// <summary>
        /// 是否能执行
        /// </summary>
        public bool CanExcuted { get; set; }

        NewArticleCmd()
        {
            CanExcuted = true;
            _requery = new RoutedCommand("New Article", typeof(NewArticleCmd));
        }

        /// <summary>
        /// 新建文章的路由命令
        /// </summary>
        public static RoutedCommand Requery
        {
            get
            {
                return Instance._requery;
            }
        }

        /// <summary>
        /// 新建文章执行代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Excuted(object sender, ExecutedRoutedEventArgs e)
        {
            Catalog selNode = ArticleManager.Instance.SelectedNode as Catalog;
            if (selNode == null)
            {
                return;
            }

            Article model = Article.CreateAsChild();
            selNode.Childs.Add(model);
            ArticleViewModel vm = new ArticleViewModel(model);
            vm.Model.ParentCatalog = selNode;
            ArticleManager.Instance.Save();
            vm.IsEditMode = true;
            AgnesServiceManager.AgnesWorkBenchService.DocumentPanels.Add(vm);
        }

        /// <summary>
        /// 判断是否能执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CanExcute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (AgnesServiceManager.AgnesSlnService.CurrentSln == null 
                || (ArticleManager.Instance.SelectedNode is Catalog) == false)
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = CanExcuted;
            }
        }
    }
}
